//
//  SeacherCarController.m
//  BalanceCar
//
//  Created by 郑信鸿 on 17/6/20.
//  Copyright © 2017年 郑信鸿. All rights reserved.
//

#import "SeacherCarController.h"
#import "SearcherCarCell.h"
#import "CarDetailController.h"
#import "MainNavigationController.h"
#import "AlertNoCarTool.h"
#import "DiffusionAnimationView.h"
#import "ByteTool.h"
#import "BaseSendData.h"
#import "CarTravelModel.h"
#import "PasswordController.h"
#import "BaseAcceptData.h"

@interface SeacherCarController ()<UITableViewDelegate,UITableViewDataSource,SearchCarCellDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic, strong)UIView *topView;

@property(nonatomic, strong)UILabel *stateLabel;

@property(nonatomic, strong)UILabel *tipLabel;

@property(nonatomic, strong)CBPeripheral *willConnectPeripheral;

@property(nonatomic, strong)AlertNoCarTool *tool;
@property(nonatomic, strong)NSMutableArray *dataList;
@property(nonatomic, strong)UITapGestureRecognizer *tap;

@property(nonatomic, strong)DiffusionAnimationView *animationView;

@property(nonatomic, assign)BOOL searching;

@property(nonatomic, assign)BOOL isAccept;

@property(nonatomic, strong)NSTimer *timer;

@end

@implementation SeacherCarController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self bulidTopLabel];
    [self bulidSubViews];
    self.dataList = [NSMutableArray array];
    //[self.dataList addObject:@""];
    [BalanceBuleManager shareManager];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(centralStateUpdata:) name:kCentralManagerStateUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(discorverPeripheral:) name:KCentralManageDiscoverPeripheralNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectPeripheral:) name:kPeripheralConentResultNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(travelDetail:) name:kPeripheraDidReadDataNotification object:nil];
    NSLog(@"%lf,%lf",kUIScreenWidth,kUIScreenHeight);
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)bulidTopLabel{
    self.stateLabel = [[UILabel alloc] init];
    [self.view addSubview:self.stateLabel];
    self.stateLabel.font = [UIFont systemFontOfSize:20];
    self.stateLabel.textAlignment = NSTextAlignmentCenter;
    self.stateLabel.text = XHLocalizedString(@"Click to search the vehicle");
    self.stateLabel.textColor = [UIColor colorFromHexCode:@"#333333"];
    [self.stateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(70);
        make.left.right.mas_offset(0);
        make.height.mas_offset(30);
    }];
    self.tipLabel = [[UILabel alloc] init];
    [self.view addSubview:self.tipLabel];
    self.tipLabel.font = [UIFont systemFontOfSize:13];
    self.tipLabel.text = XHLocalizedString(@"Please make sure the vehicle close to the cellphone");
    self.tipLabel.textAlignment = NSTextAlignmentCenter;
    self.tipLabel.textColor = [UIColor lightGrayColor];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.mas_equalTo(self.stateLabel.mas_bottom).offset(10);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(12);
        
    }];
}


- (void)bulidSubViews{
    //CGFloat heightRatio = 0.7;
     CGFloat topHeight = 320;
    if (kUIScreenHeight == 480) {
        
        topHeight = 200;
    }
   // CGFloat tableViewHeight = kUIScreenHeight *(1 - heightRatio);
  
    self.topView = [[UIView alloc] init];
    [self.view addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.mas_offset(0);
        make.right.mas_offset(0);
        make.top.mas_equalTo(self.stateLabel.mas_bottom).offset(40);
        make.height.mas_offset(topHeight);
        
    }];
    [self bulidTopView];
    //tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.mas_offset(0);
        make.right.mas_offset(0);
        make.top.mas_equalTo(self.topView.mas_bottom).offset(0);
        make.bottom.mas_offset(-10);
        
    }];
    [self.tableView registerClass:[SearcherCarCell class] forCellReuseIdentifier:@"SearcherCarCell"];
    self.tableView.rowHeight = 70;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
}


- (void)bulidTopView{
    self.animationView = [[DiffusionAnimationView alloc] init];
    [self.topView addSubview:self.animationView];
//    CGFloat x = (kUIScreenWidth - 180)/2.0;
//    CGFloat y = (320 - 180)/2.0;
//    self.animationView.frame = CGRectMake(x, y, 180, 180);
    [self.animationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_offset(0);
        make.width.height.mas_offset(180);
    }];
    //180x180
    UIImageView *findbgImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"find_bg"]];
    self.tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(searchAction:)];
    [self.animationView addGestureRecognizer:self.tap];
    [self.topView addSubview:findbgImage];
    [findbgImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_offset(0);
    }];
    UIImageView *findIconImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"find_bg_car"]];
    [self.topView addSubview:findIconImage];
    [findIconImage mas_makeConstraints:^(MASConstraintMaker *make) {
       make.center.mas_offset(0);
    }];
    
    
}



#pragma tableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearcherCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearcherCarCell" forIndexPath:indexPath];
    NSDictionary *dict = self.dataList[indexPath.row];
    CBPeripheral *peripheral = dict[@"peripheral"];
    cell.carNameLabel.text = [NSString stringWithFormat:@"%@",peripheral.name];
    cell.delegate = self;
    cell.line.hidden = NO;
    if (self.dataList.count == 1) {
        
        [cell setAllCorner];
        cell.line.hidden = YES;
        
    }else{
        
        if (indexPath.row == 0) {
            
            [cell setTopCorner];
            
        }else if (indexPath.row == self.dataList.count - 1) {
            
            [cell setBottomCorner];
            cell.line.hidden = YES;
            
        }else{
            
            [cell setNoCorner];
        }
    }
   
    return cell;
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    CarDetailController *col = [[CarDetailController alloc] init];
//    MainNavigationController *navCol = [[MainNavigationController alloc] initWithRootViewController:col];
//    
//    [self presentViewController:navCol animated:YES completion:^{
//        
//    }];
//    
//}

- (void)searchCarCell:(SearcherCarCell *)cell WithModel:(id)mode{
 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSDictionary *dict = self.dataList[indexPath.row];
    CBPeripheral *peripheral = dict[@"peripheral"];
    self.willConnectPeripheral = peripheral;
    [LTCSingleHud showLoading:nil];
    [[BalanceBuleManager shareManager] conentPeripherals:peripheral];
    
}


- (void)searchAction:(UITapGestureRecognizer *)tap{
    if (self.searching) {
       
        [[BalanceBuleManager shareManager] stopScan];
        [self.animationView stopAnimation];
        self.searching = NO;
        
    }else{
        
        [self.animationView startAnimation];
        [[BalanceBuleManager shareManager]scanPeripherals];
        self.searching = YES;
    }
   
    
}

#pragma mark Notification
//蓝牙变化
- (void)centralStateUpdata:(NSNotification *)notic{
    NSDictionary *dict = notic.object;
    CBCentralManager *central = dict[@"central"];
    NSString *info = nil;
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            info = @"蓝牙已打开，并且可用";
            if ([[BalanceBuleManager shareManager]autoConnectPeripherals] ) {
                
                return;
            }
            
            break;
        case CBCentralManagerStatePoweredOff:
            info = @"蓝牙可用，未打开";
            break;
        case CBCentralManagerStateUnsupported:
            info = @"SDK不支持";
            break;
        case CBCentralManagerStateUnauthorized:
            info = @"程序未授权";
            break;
        case CBCentralManagerStateResetting:
            info = @"CBCentralManagerStateResetting";
            break;
        case CBCentralManagerStateUnknown:
            info = @"CBCentralManagerStateUnknown";
            break;
    }
    //[LTCSingleHud showMessage:info];
}

//发现设备
- (void)discorverPeripheral:(NSNotification *)notice{
    
    NSDictionary *dict = notice.object;
    if (dict) {
        
        if (self.dataList.count == 0) {
            
            [self.dataList addObject:dict];
            
        } else {
            CBPeripheral *peripheral = dict[@"peripheral"];
            BOOL isExist = NO;
            for (int i = 0; i < self.dataList.count; i++) {
                NSDictionary *tempDict = [self.dataList objectAtIndex:i];
                CBPeripheral *per = tempDict[@"peripheral"];
                if ([per.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
                    isExist = YES;
                    [self.dataList replaceObjectAtIndex:i withObject:dict];
                }
            }
            if (!isExist) {
        
                [self.dataList addObject:dict];
            }
        }
        
        [self.tableView reloadData];
        
    }else{
        
        __weak typeof(self) weakSelf = self;
        self.tool = [[AlertNoCarTool alloc] initWithTouchBlock:^(id value) {
            
            [weakSelf searchAction:nil];
            
        }];
        [self.tool showView];
        
        [self.animationView stopAnimation];
        
    }
}

//连接设备结果
- (void)connectPeripheral:(NSNotification *)notice{
    
    [LTCSingleHud hideHud];
    
    NSDictionary *dict = notice.object;
    
    if (dict) {
        
        NSInteger result = [dict[@"connect"] integerValue];
        
        if (!result) {
            
            [self.animationView stopAnimation];
            self.isAccept = NO;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction) userInfo:self repeats:YES];
           
            
        }else{
            
            //[LTCSingleHud showMessage:XHLocalizedString(@"Connect Fault")];

        }
        
    }
    
    
    
}


- (void)sendPassword{
    
    NSString *password = @"0000";
    Byte pwbytes[6] = {};
    [ByteTool hexString:password pwbytes:pwbytes];
    [BaseSendData sendConnectPw:pwbytes];
}

- (void)travelDetail:(NSNotification *)notice{
    
    if (self.isAccept) {
        return;
    }
    ResultModel *model = notice.object;
    if (model.dataType == InputPasswordType) {
        self.isAccept = YES;
        NSInteger code = [BaseAcceptData feedbackSuccessWithdata:model.data];
        if (code == 1) {
            
            [self.tableView reloadData];
            
            CarDetailController *col = [[CarDetailController alloc] init];
            MainNavigationController *navCol = [[MainNavigationController alloc] initWithRootViewController:col];
            
            [self presentViewController:navCol animated:YES completion:^{
                
            }];
            
            
        }else{
            
            PasswordController *col = [[PasswordController alloc] initWithComplete:^(NSInteger code) {
                
                if (code == 1) {
                    
                    [self.dataList removeAllObjects];
                    
                    [self.tableView reloadData];
                    
                    CarDetailController *col = [[CarDetailController alloc] init];
                    MainNavigationController *navCol = [[MainNavigationController alloc] initWithRootViewController:col];
                    
                    [self presentViewController:navCol animated:YES completion:^{
                        
                    }];
                }
                
            }];
            
            [self presentViewController:col animated:YES completion:^{
                
            }];
            
        }
        
    }
    
    
}

- (void)timerAction{
    
    if (!self.isAccept) {
        [self sendPassword];
    }else{
        
        [self.timer invalidate];
        self.timer = nil;
    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
